package alarm;

import java.util.Date;
import java.util.Scanner;
import java.util.TimerTask;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.*;
import gui.Data;
import gui.Login;
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileNotFoundException;
import java.util.*;

public class Alarm extends TimerTask {

	ArrayList<Data> arrayList = new ArrayList<Data>();
	JFrame reminder = new JFrame("reminder");
	JTextArea text = new JTextArea(5, 3);
	JScrollPane scroll = new JScrollPane(text);
	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
	Date date = new Date();
	String currentDate = dateFormat.format(date);
	public Alarm() {
		reminder.setSize(300, 200);
		reminder.setLocation(500, 280);
		reminder.add(scroll);
		reminder.setResizable(false);
		reminder.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		text.setEditable(false);
		reminder.setVisible(true);
		text.setBackground(null);
		scroll.setBackground(null);
	}

	public void run() {
		readFile(currentDate);
		if(arrayList.size() == 0){
			reminder.setVisible(false);
			return;
		}
		if(!reminder.isVisible())
			reminder.setVisible(true);
		String content = "";
		for (Data d : arrayList){
			content += d.getTitle() + ": " + d.getDetail() + "\n";
		}
		text.setText(content);
	}

	private File[] getList() {
		File dir = new File(Login.data_dir);
		File[] files = dir.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".txt")
						&& name.toLowerCase().startsWith(Login.user + "-");
			}
		});
		return files;
	}

	public void readFile(String currentDate) {
		File[] files = getList();
		arrayList.clear();
		for (File f : files) {
			try {
				Scanner scanFile = new Scanner(f);
				String title = scanFile.nextLine(); // Title
				String date = scanFile.nextLine(); // Date
				if (!date.equals(currentDate)) {
					scanFile.close();
					continue;
				}
				String group = scanFile.nextLine(); // Group
				String detail = scanFile.nextLine(); // Detail
				while (scanFile.hasNext())
					detail += "\n" + scanFile.nextLine();
				Data d = new Data(f.getName(), title, date, group, detail);
				arrayList.add(d);
				scanFile.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}